﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.Routing;
using NHibernate;
using SAKS.ViewModels;
using SAKS.Models;
using SAKS.IServices;
using SAKS.ActionFilters;


using Microsoft.Practices.Unity;
using SAKS.ConfigManager;


namespace SAKS.Controllers
{
    
    public class AccountController : ControllerBase
    {
        public IFormsAuthenticationServices FormsServices { get; set; }
        public IMembershipServices MembershipServices { get; set; }
        public IRoleServices RoleServices { get; set; }
        public IMessageServices MessageServices { get; set; }


        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            MembershipServices.Session = GetCurrentSession(requestContext);
            RoleServices.Session = GetCurrentSession(requestContext);
            MessageServices.Session = GetCurrentSession(requestContext);
        }


        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipServices.ValidateUser(model.UserName, model.Password))
                {
                    FormsServices.SignIn(model.UserName, model.RememberMe,RoleServices.GetRolesForUser(model.UserName));

                    HttpContext.Session["username"] = model.UserName;
                    HttpContext.Session["unreadmessagecount"] = MessageServices.GetMessagesUnReadCount(model.UserName);


                    string ReturnUrl = Request["ReturnUrl"];
                    if (Url.IsLocalUrl(ReturnUrl))
                    {
                        return Redirect(ReturnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "用户名或密码不正确.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [Authorize]
        public ActionResult LogOff()
        {
            FormsServices.SignOut();

            return RedirectToAction("Index", "Home");
        }

        public ActionResult Register()
        {
            return View();
        }

        [NeedsPersistence]
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipServices.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsServices.SignIn(model.UserName, false ,new List<string>());
                    return RedirectToAction("CreateInfo","User");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            return View(model);
        }

        [NeedsPersistence]
        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (model.NewPassword == model.ConfirmPassword)
            {
                if (MembershipServices.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return Json(new AjaxResponse { Message = "修改成功", State = "Succeed" });
                }
                else
                {
                    return Json(new AjaxResponse { Message = "修改失败 - 旧密码输入不正确", State = "Failure" });
                }
            }
            return Json(new AjaxResponse { Message = "修改失败 - 新密码两次输入不一致", State = "Failure" });
        }

        public JsonResult AjaxUsernameShouldntExist(string fieldId, string fieldValue)
        {
            object[] result = new object[2];
            result[0] = fieldId;
            if (MembershipServices.IsUserExist(fieldValue))
            {
                result[1] = false;
            }
            else
                result[1] = true;
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult AjaxUsernameShouldExist(string fieldId, string fieldValue)
        {
            object[] result = new object[2];
            result[0] = fieldId;
            if (MembershipServices.IsUserExist(fieldValue))
            {
                result[1] = true;
            }
            else
                result[1] = false;
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}
